<template>
  <a-card :bordered="false" ref="card">
    <GanttElastic class="gantt-elastic-outer" :tasks="tasks" :options="options" v-if="tasks.length">
      <GanttHeader :options="headerOptions" slot="header" :tasks="tasks" ></GanttHeader>
    </GanttElastic>
    <div class="plan-empty" v-else :style="{height:height+'px'}">
      <div class="empty-title">暂无数据</div>
      <div class="empty-subtitle">请添加相关工作计划</div>
    </div>
    <ScheduleModal ref="modalForm"></ScheduleModal>
    <ScheduleNodeInfoModal ref="infoModalForm"></ScheduleNodeInfoModal>
  </a-card>
</template>

<script>
import GanttElastic from '@/components/gantt/GanttElastic'
import GanttHeader from '@/components/gantt/GanttHeader'
import ScheduleModal from './modules/ScheduleModal'
import ScheduleNodeInfoModal from './modules/ScheduleNodeInfoModal'
import { getPlanListWithContents } from '@/services/schedule'
import moment from 'moment'
export default {
  name: 'ScheduleDashboard',
  components: { GanttElastic, GanttHeader, ScheduleModal, ScheduleNodeInfoModal },
  data() {
    return {
      height: 500,
      headerOptions: {
        title: { label: '重点工作计划看板' },
        locale: {
          Now: '现在',
          'Display task list': '显示计划列表'
        }
      },
      tasks: [],
      options: {
        // maxRows: 3,
        maxHeight: '100%',
        minHeight: '100%',
        title: {
          label: '重点项目看板',
          html: false
        },
        row: {
          height: 36
        },
        calendar: {
          hour: {
            display: false
          }
        },
        chart: {
          progress: {
            bar: false
          },
          expander: {
            display: true
          }
        },
        taskList: {
          expander: {
            straight: false
          },
          columns: [
            {
              label: '分解来源',
              value: 'source',
              width: 100,
              expander: true,
              html: true
            },
            {
              label: '工作大类',
              value: (task) => {
                return `
                <a href="javascript:void(0);">
                  ${task.category || ''}  
                </a>
                `
              },
              width: 100,
              html: true,
              events: {
                click: ({ data, column }) => {
                  this.handleScheduleModal(data, column)
                }
              }
            },
            {
              label: '计划节点内容',
              value: (task) => {
                return `
                <a href="javascript:void(0);">
                  ${task.content || ''}  
                </a>
                `
              },
              width: 100,
              html: true,
              events: {
                click: ({ data, column }) => {
                  this.handleScheduleInfoModal(data, column)
                }
              }
            },
            {
              label: '起止时间',
              value: (task) => {
                return `
                  <p class="gantt-start-end-time">${moment(task.startTime).format('YYYY-MM-DD')}</p>
                  <p class="gantt-start-end-time">${moment(task.endTime).format('YYYY-MM-DD')}</p>
                `
              },
              width: 100,
              html: true
            },
            {
              label: '总/子计划进度',
              value: (task) => {
                let res = '-'
                if (task.type === 'project') {
                  res = task.totalProgress
                } else {
                  res = task.subProgress ? `${task.subProgress}%` : '-'
                }
                return res
              },
              width: 100,
              style: {
                'task-list-header-label': {
                  'text-align': 'center',
                  width: '100%'
                },
                'task-list-item-value-container': {
                  'text-align': 'center',
                  width: '100%'
                }
              }
            },
            {
              label: '是否完成',
              value: (task) => task.type === 'project' ? '-' : task.status === '1' ? `已完成` : '未完成',
              width: 80,
              style: {
                'task-list-header-label': {
                  'text-align': 'center',
                  width: '100%'
                },
                'task-list-item-value-container': {
                  'text-align': 'center',
                  width: '100%'
                }
              }
            }
          ]
        }}
    }
  },
  mounted() {
    this.loadData()
    setTimeout(() => {
      this.setTableHeight()
    }, 200)
  },
  watch: {
    $route(to, from) {
      if (to.path === '/schedule/schedule-dashboard' && from.path !== '/schedule/schedule-dashboard') {
        this.loadData()
      }
    }
  },
  methods: {
    setTableHeight() { // 设置页面表格高度
      if (this.$refs.card) {
        const clientHeight = document.documentElement.clientHeight
        const tableTop = this.$refs.card.$el.getBoundingClientRect().top
        this.height = clientHeight - tableTop - 40
      }
    },
    async loadData() {
      const res = await getPlanListWithContents(moment().year().toString())
      if (res && res.code !== 200) {
        // VXETable.modal.message({ content: '获取数据失败', status: 'error' })
        return
      }
      const taskList = this.formatData(res.result)
      this.tasks = taskList
    },
    formatData(data) {
      const res = [];
      (data || []).forEach(item => {
        const { contentList, ...rest } = item
        const progress = Math.min(Math.ceil(contentList.filter(item => item.status === '1').length / contentList.length * 100), 100)
        res.push({
          ...rest,
          progress,
          totalProgress: `${contentList.filter(item => item.status === '1').length} / ${contentList.length}`,
          endTime: moment(rest.endTime),
          startTime: moment(rest.startTime),
          type: 'project'
        })
        if (Array.isArray(contentList) && contentList.length) {
          const _contentList = [...contentList].reverse()
          _contentList.forEach((node, idx) => {
            const lastId = idx ? res[res.length - 1].id : 0
            res.push({
              ...node,
              subProgress: node.progress,
              progress: node.status === '1' ? 100 : 0,
              parentId: rest.id,
              type: 'milestone',
              endTime: moment(node.endTime),
              startTime: moment(node.startTime),
              dependentOn: lastId ? [lastId] : [],
              style: {
                base: {
                  fill: '#1EBC61',
                  stroke: '#0EAC51'
                }
              }
            })
          })
        }
      })
      return res
    },
    handleScheduleModal(data, column) {
      const req = {
        ...data,
        responsibleDpt: data.mgrDept.map(item => item.deptName),
        responsibleDepts: data.mgrDept.map(item => item.deptCode).join(','),
        startEndTime: [data.startTime, data.endTime]
      }
      this.$refs.modalForm.edit(req)
      this.$refs.modalForm.title = '查看计划'
      this.$refs.modalForm.disableSubmit = true
    },
    handleScheduleInfoModal(data, column) {
      const { progress, startTime, endTime, deptList } = data
      const leadingDept = deptList.find(item => item.deptType === '1')
      const cooperateDept = deptList.filter(item => item.deptType === '2').map(item => ({ ...item, id: item.deptId }))
      if (leadingDept) {
        leadingDept.id = leadingDept.deptId
      }
      const req = {
        ...data,
        progress: progress ? `${progress}%` : '0%',
        startTime: moment.isMoment(startTime) ? startTime.format('YYYY-MM-DD') : startTime,
        endTime: moment.isMoment(endTime) ? endTime.format('YYYY-MM-DD') : endTime,
        leadingDept: leadingDept ? leadingDept.deptName : null,
        cooperateDept: cooperateDept.map(item => item.deptName).join(','),
        attachList: [],
        _leadingDept: leadingDept,
        _cooperateDept: cooperateDept
      }
      this.$refs.infoModalForm.edit(req)
      this.$refs.infoModalForm.title = '查看计划节点'
      this.$refs.infoModalForm.disableSubmit = true
    }
  }
}
</script>
<style>
.gantt-start-end-time {
  margin: 0;
}
.gantt-elastic-outer {
  height: 100%;
}
.plan-empty {
  margin: 100px 0;
}
.empty-title {
  color: rgba(0,0,0,.85);
  font-size: 24px;
  line-height: 1.8;
  text-align: center;
}
.empty-subtitle {
  color: rgba(0,0,0,.45);
  font-size: 14px;
  line-height: 1.6;
  text-align: center;
}
</style>
